package com.esm.sm800.sm800floating;

import com.esm.sm800.R;
import android.os.AsyncTask;
import android.os.Build;

import androidx.annotation.RequiresApi;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FtpUploadUtil  extends AsyncTask<Void, Void, Boolean> {
    private String server = "192.168.111.116";
    private int port = 21;
    private String user = "cgh_desktop";
    private String pass = "123";
    private String SourcefileFullPathName;
    private String DestFTPfileName;
    private Boolean isTest = false;

    public FtpUploadUtil(String server, String user, String pass, String SourcefileFullPathName, String DestFTPfileName, Boolean isTest) {
        this.server = server;
        this.user = user;
        this.pass = pass;
        this.SourcefileFullPathName = SourcefileFullPathName;
        this.DestFTPfileName = DestFTPfileName;
        this.isTest = isTest;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected Boolean doInBackground(Void... voids) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            System.out.println("Connected to FTP server: " + server);
            ftpClient.login(user, pass);
            ftpClient.enterLocalPassiveMode(); // 尝试使用被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            if(isTest){
                ftpClient.logout();
                ftpClient.disconnect();
                return true;
            }

            File firstLocalFile = new File(SourcefileFullPathName);
            System.out.println("File input stream created: " + (firstLocalFile != null));
            InputStream fis = new FileInputStream(firstLocalFile);

            boolean success = ftpClient.storeFile(DestFTPfileName , fis);
            fis.close();

            if (success) {
                System.out.println("The file has been uploaded successfully.");
            } else {
                System.out.println("The file has failed to upload.");
            }
            ftpClient.logout();
            ftpClient.disconnect();
            return success;
        } catch (IOException ex) {
            ex.printStackTrace();
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex2) {
                ex2.printStackTrace();
            }
        }
        return false;
    }
}
